﻿using System;
using System.Collections.Generic;

namespace Mbs.Factories
{
    public interface IFactoryRepository<TInput>
    {
        /// <summary>
        /// 通过工厂
        /// </summary>
        IFactory Get(TInput input);

        /// <summary>
        /// 注册工厂
        /// </summary>
        /// <param name="factory"></param>
        void Register(TInput input, IFactory factory);

        /// <summary>
        /// 清空所有元素
        /// </summary>
        void Clear();
    }
   
    [Serializable]
    public class FactoryRepository<TInput> : MarshalByRefObject, IFactoryRepository<TInput>
    {
        public FactoryRepository()
        {
            Factories = new Dictionary<TInput, IFactory>();
        }

        protected IDictionary<TInput, IFactory> Factories { get; private set; }

        public virtual IFactory Get(TInput input)
        {
            IFactory result = null;
            Factories.TryGetValue(input, out result);
            return result;
        }

        public void Register(TInput input, IFactory factory)
        {
            if (input == null)
                throw new ArgumentNullException("input");
            if (factory == null)
                throw new ArgumentNullException("factory");

            Factories[input] = factory;
        }

        public void Clear()
        {
            Factories.Clear();
        }
    }

   
}
